package myhomework;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

/*用反射去创建一个对象，有2种方式，尽量用代码去体现*/
public class Test2 {
    public static void main(String[] args) throws Exception {
        //第一种
        Class clazz = Class.forName("myhomework.Student");
        Student student = (Student) clazz.newInstance();
        Field nameField = clazz.getDeclaredField("name");
        Field ageField = clazz.getDeclaredField("age");
        nameField.setAccessible(true);
        ageField.setAccessible(true);
        nameField.set(student,"路明非");
        ageField.set(student,20);
        System.out.println(student);

        Method setName = clazz.getMethod("setName", String.class);
        Method setAge = clazz.getMethod("setAge", int.class);
        setName.invoke(student,"楚子航");
        setAge.invoke(student,18);
        System.out.println(student);
        //第二种
        Constructor constructor = clazz.getConstructor(String.class, int.class);
        Student stu = (Student) constructor.newInstance("路明泽", 18);
        System.out.println(stu);
    }
}
